package cn.caplike.demo.rabbitmq.api.exchange.default_;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

import static cn.caplike.demo.rabbitmq.api.Application.RABBITMQ_HOST;
import static cn.caplike.demo.rabbitmq.api.Application.RABBITMQ_PORT;

/**
 * AMQP 核心概念<br>
 * Server: 又称 Broker, 接受客户端的连接, 实现 AMQP 实体服务
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-02-18 14:44
 */
public class Consumer4DefaultExchange {
    private final static String QUEUE_NAME = "test001";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建一个链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(RABBITMQ_HOST);
        connectionFactory.setPort(RABBITMQ_PORT);
        connectionFactory.setVirtualHost("/");

        // 通过链接工厂创建连接
        // 连接, 应用程序与 Broker 的网络连接
        Connection connection = connectionFactory.newConnection();

        // 通过连接创建一个 Channel
        // 网络信道, 几乎所有的操作都在 Channel 中进行, Channel 是进行消息读写的通道.
        // 客户端可以建立多个 Channel, 每个 Channel 代表一个会话任务
        Channel channel = connection.createChannel();

        // 声明一个队列
        // exclusive: 表示这个队列只能被这一个 Channel 监听. 场景: 集群环境下的顺序消息
        channel.queueDeclare(QUEUE_NAME, false, false, true, null);
        System.out.println("Waiting for message ...");

        // https://www.rabbitmq.com/tutorials/tutorial-one-java.html
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("Received '" + message + "'");
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, System.out::println);

    }
}
